<?php

namespace app\admin\controller\dahui;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 企业普通管理
 *
 * @icon fa fa-circle-o
 */
class Qiyeputong extends Backend
{
    
    /**
     * Qiyeputong模型对象
     * @var \app\admin\model\dahui\Qiyeputong
     */
    protected $model = null;

    protected $searchFields = 'id,idnumber,ownedcompany,qiyekehu.name,qiyekehu.mobile';

    protected $noNeedRight = ['saveadd', 'cxselect', 'index1', 'index1list', 'index2', 'changetype', 'changetstatus', 'changetypepl', 'changetstatuspl','zrxy', 'xgjs', 'getuserinfo'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dahui\Qiyeputong;
        $this->view->assign("businesstypeList", $this->model->getBusinesstypeList());

        $this->assignconfig('audit', $this->auth->check('dahui/dingdan/audit'));
        $this->assignconfig('luru', $this->auth->check('dahui/dingdan/luru'));
        $this->assignconfig('caozuo', $this->auth->check('dahui/dingdan/caozuo'));

        $this->assignconfig('tuikuan', $this->auth->check('dahui/newtk/tuikuan'));

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                    ->with(['qiyekehu','qiyenianyue'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $money = $this->model
                ->with(['qiyekehu','qiyenianyue'])
                ->where($where)
                ->order($sort, $order)
                ->sum('qiyenianyue.paymentamount');

            $list = $this->model
                    ->with(['qiyekehu','qiyenianyue'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as &$row) {
                $row->id = $row->qiyenianyue->id; //使用年月的id
            }
            $list = collection($list)->toArray();

            if ($limit == 0) {
                //导出
//                foreach ($list as &$row) {
//                    $row['idnumber'] = $this->importstr($row['idnumber']);
//                    $row['paymentnumber'] = $this->importstr($row['paymentnumber']);
//                }
            }

            $result = array("total" => $total, "rows" => $list, "extend" => ['money' => sprintf("%.2f", $money)]);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function importstr($one) {

        return "' ".$one;
    }


    //企业普通明细表单
    public function index1()
    {

        $idnumber = $this->request->get("idnumber", '');
        $row = \app\admin\model\dahui\Qiyekehu::where('idnumber', $idnumber)->find();

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params = $this->setquanxianlog($params);
            $result = $row->allowField(true)->save($params);
            $this->success('修改成功');
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    //企业普通明细-列表
    public function index1list() {

        if ($this->request->isAjax()) {
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);

            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);

            $idnumber = $this->request->get("idnumber", '');
            $row = \app\admin\model\dahui\Qiyekehu::where('idnumber', $idnumber)->find();

            $list = [];
            $gplist = $this->model
                ->where('idnumber', $idnumber)
                ->select();

            foreach ($gplist as &$gp) {
                $nlist = collection(\app\admin\model\dahui\Qiyenianyue::where('businessnumber', $gp['businessnumber'])
                    ->select())->toArray();

                foreach ($nlist as $nianyue) {
                    $nianyue['ownedcompany'] = $gp->ownedcompany;
                    $nianyue['contractperiod_from'] = $gp->contractperiod_from;
                    $nianyue['contractperiod_to'] = $gp->contractperiod_to;
                    $nianyue['businesstype'] = $gp->businesstype;
                    $nianyue['paymentnumber'] = $gp->paymentnumber;

//                    if ($limit == 0) {
//                        //导出
//                        $nianyue['idnumber'] = $this->importstr($nianyue['idnumber']);
//                        $nianyue['paymentnumber'] = $this->importstr($nianyue['paymentnumber']);
//                    }

                    $list[] = $nianyue;
                }
            }

            $result = array("total" => count($list), "rows" => $list);

            return json($result);
        }
    }

    public function index2()
    {
        //http://dahui.test/admin/dahui/qiyeputong/index2/businessnumber/1731?dialog=1
        $url = $_SERVER['HTTP_REFERER'];
        if (false !== strpos($url, '/businessnumber/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $businessnumber = $urls[$size - 1];
        }

        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['qiyekehu'])
                ->where($where)
                ->where('qiyeputong.businessnumber', $businessnumber)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['qiyekehu'])
                ->where($where)
                ->where('qiyeputong.businessnumber', $businessnumber)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $row = $this->model
                        ->where('businesstype', $params['businesstype'])
                        ->where('idnumber', $params['idnumber'])
                        ->find();

                    $params = $this->setquanxianlog($params);
                    if (!$row) {
                        $result = $this->model->allowField(true)->save($params);
                        $this->model->businessnumber = $this->model->id;
                        $this->model->save();
                        $params['businessnumber'] = $this->model->id;
                    } else {
                        $params['businessnumber'] = $row->businessnumber;
                        $row1 = new \app\admin\model\dahui\Qiyeputong;
                        $result = $row1->allowField(true)->save($params);
                    }

                    $kehu = \app\admin\model\dahui\Qiyekehu::get(['idnumber' => $params['idnumber']]);
                    if (!$kehu) {
                        $kehu = new \app\admin\model\dahui\Qiyekehu;
                    }
                    $result2 = $kehu->allowField(true)->save($params);

                    $nymodel = new \app\admin\model\dahui\Qiyenianyue();

                    //SELECT * FROM `fa_dahui_qiyenianyue` WHERE  `businessnumber` = '678'  AND `yearpayment` = '2022-06'  AND `type` <> '转出'
                    $ny = $nymodel->where('businessnumber', $params['businessnumber'])
                        ->where('yearpayment', $params['yearpayment'])
                        ->where('type', '<>', '转出')
                        ->find();

                    if ($ny) {
                        $this->error(__('添加失败，系统已存在该客户该业务缴纳年月！'));
                    } else {
                        $result3 = $nymodel->allowField(true)->save($params);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $Gongshi = new \app\admin\model\dahui\Gongshi;
        $companyList = collection($Gongshi->field('businesstype, name, minimumcardinality, proportion')->select())->toArray();
        $this->view->assign("companyList", $companyList);

        return $this->view->fetch();
    }

    //添加已使用ajax单独处理
    public function saveadd()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $row = $this->model
                        ->where('businesstype', $params['businesstype'])
                        ->where('idnumber', $params['idnumber'])
                        ->find();

                    $params = $this->setquanxianlog($params);
                    if (!$row) {
                        $result = $this->model->allowField(true)->save($params);
                        $this->model->businessnumber = $this->model->id;
                        $this->model->save();
                        $params['businessnumber'] = $this->model->id;
                    } else {
                        $result = $row->allowField(true)->save($params);
                        $params['businessnumber'] = $row->businessnumber;
                    }

                    $kehu = \app\admin\model\dahui\Qiyekehu::get(['idnumber' => $params['idnumber']]);
                    if (!$kehu) {
                        $kehu = new \app\admin\model\dahui\Qiyekehu;
                    }
                    $result2 = $kehu->allowField(true)->save($params);

                    $nymodel = new \app\admin\model\dahui\Qiyenianyue();

                    $ny = $nymodel->where('businessnumber', $params['businessnumber'])
                        ->where('yearpayment', $params['yearpayment'])
                        ->where('type', '<>', '转出')
                        ->find();

                    if ($ny) {
                        $this->error(__('添加失败，系统已存在该客户该业务缴纳年月！'));
                    } else {
                        $result3 = $nymodel->allowField(true)->save($params);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
//                    $this->success();
//                    $this->error("已添加成功, 继续加油！", null, '', 1);
                    $this->success("已添加成功！");
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }

    /**
     * 编辑 订单管理
     */
    public function edit($ids = null)
    {
        $ny = \app\admin\model\dahui\Qiyenianyue::get($ids);
        if (!$ny) {
            $this->error(__('No Results were found'));
        }

        $row = $this->model
            ->where('businessnumber', $ny->businessnumber)
            ->find();

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if (isset($params['qiyenianyue.note'])) {
                    $ny->note = $params['qiyenianyue.note'];
                    $ny = $this->setquanxianlog2($ny);
                    $ny->save();
                    $this->success();
                } else if (isset($params['paymentnumber'])) {
                    $params = $this->setquanxianlog($params);
                    $result = $row->allowField(true)->save($params);
                    $this->success();
                }

                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $params = $this->setquanxianlog($params);
                    $result = $row->allowField(true)->save($params);
                    $params['businessnumber'] = $row->businessnumber;

                    $kehu = \app\admin\model\dahui\Qiyekehu::get(['idnumber' => $row->idnumber]);
                    if (!$kehu) {
                        $this->error(__('未找到企业客户！'));
                    }
                    $result2 = $kehu->allowField(true)->save($params);

                    $nymodel = new \app\admin\model\dahui\Qiyenianyue();
                    $ny = $nymodel->where('businessnumber', $params['businessnumber'])
                        ->where('yearpayment', $params['yearpayment'])
                        ->find();

                    if ($ny) {
                        $result3 = $ny->allowField(true)->save($params);
                    } else {
                        $result3 = $nymodel->allowField(true)->save($params);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $Gongshi = new \app\admin\model\dahui\Gongshi;
        $companyList = collection($Gongshi->field('businesstype, name, minimumcardinality, proportion')->select())->toArray();
        $this->view->assign("companyList", $companyList);

        $kehu = \app\admin\model\dahui\Qiyekehu::get(['idnumber' => $row['idnumber']]);
        if ($kehu) {
            $row['idnumber'] = $kehu->idnumber;
            $row['name'] = $kehu->name;
            $row['mobile'] = $kehu->mobile;
            $row['address0'] = $kehu->address0;
            $row['address1'] = $kehu->address1;
            $row['note'] = $kehu->note;
        }

        if ($ny) {
            $row['payingcompany'] = $ny->payingcompany;
            $row['paymentbase'] = $ny->paymentbase;
            $row['paymentamount'] = $ny->paymentamount;
            $row['yearpayment'] = $ny->yearpayment;
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {

            $ny = \app\admin\model\dahui\Qiyenianyue::get($ids);
            if (!$ny) {
                $this->error(__('No rows were deleted'));
            }

            $ny->delete();
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 办理类型++
     */
    //http://dahui.test/admin/dahui/dingdan/changetype
    public function changetype($ids = null)
    {
        $ny = \app\admin\model\dahui\Qiyenianyue::get($ids);
        if (!$ny) {
            $this->error(__('No Results were found'));
        }

        if ($ny->type == '新入') {
            $ny->type = '续费';
            $this->dealnext($ny, 1);
        } else if ($ny->type == '续费') {
            $ny->type = '转出';
            $this->dealnext($ny, 2);
        } else if ($ny->type == '转出') {
            $ny->type = '新入';
            $this->dealnext($ny, 1);
        }

        $ny->save();
        $this->success("办理类型修改成功", null, ['type' => $ny->type]);
    }

    public function changetypepl($ids = null, $type)
    {
        $list = \app\admin\model\dahui\Qiyenianyue::where('id', 'in', $ids)->select();
        foreach ($list as &$ny) {

            if ($type == 0) {
                $ny->type = '新入';
            } else if ($type == 1) {
                $ny->type = '续费';
            } else if ($type == 2) {
                $ny->type = '转出';
                //删除下个月的记录
            }
            $this->dealnext($ny, $type);
            $ny->save();
        }

        $this->success("办理类型修改成功");
    }

    function dealnext($ny, $type)
    {
        $nextmoth = date("Y-m", strtotime("+1 months", strtotime($ny['yearpayment'])));
        $ny1 = \app\admin\model\dahui\Qiyenianyue::where('yearpayment', $nextmoth)->where('businessnumber', $ny['businessnumber'])->find();
        if ($ny1) {
            if ($type == 2) {
                $ny1->delete();
            }
        } else {
            if ($type < 2) {
                $ny1 = new \app\admin\model\dahui\Qiyenianyue();
                $ny1->businessnumber = $ny->businessnumber;
                $ny1->yearpayment = $nextmoth;
                $ny1->payingcompany = $ny->payingcompany;
                $ny1->paymentbase = $ny->paymentbase;
                $ny1->paymentamount = $ny->paymentamount;
                $ny1->type = '续费';
                $ny1->save();
            }
        }
    }

    /**
     * 办理状态++
     */
    //http://dahui.test/admin/dahui/dingdan/changetstatus
    public function changetstatus($ids = null)
    {
        $ny = \app\admin\model\dahui\Qiyenianyue::get($ids);
        if (!$ny) {
            $this->error(__('No Results were found'));
        }

        if ($ny->status == '未办理') {
            $ny->status = '已办理';
        } else if ($ny->status == '已办理') {
            $ny->status = '办理失败';
        } else if ($ny->status == '办理失败') {
            $ny->status = '未办理';
        }

        $ny->save();
        $this->success("办理状态修改成功", null, ['status' => $ny->status]);
    }

    public function changetstatuspl($ids = null, $type)
    {
        $list = \app\admin\model\dahui\Qiyenianyue::where('id', 'in', $ids)->select();
        foreach ($list as &$ny) {
            if ($type == 0) {
                $ny->status = '未办理';
            } else if ($type == 1) {
                $ny->status = '已办理';
            } else if ($type == 2) {
                $ny->status = '办理失败';
            }
            $ny->save();
        }

        $this->success("办理状态修改成功");
    }

    //http://dahui.test/admin/dahui/qiyeputong/zrxy?yearpayment=2019-07
    //定时，每月1日 05:00 转入
    public function zrxy()
    {
        $thismoth = $this->request->get('yearpayment', '');
        if (empty($thismoth)) {
            $this->error("无效的转入年月！");
        }

        $nextmoth = date("Y-m", strtotime("+1 months", strtotime($thismoth)));

        $sql = "truncate table aa";
        Db::execute($sql);

        $sql = "insert into aa (select businessnumber, '{$nextmoth}' as yearpayment, payingcompany, paymentbase, paymentamount, ''note,
case when CONCAT(type,status)='新入办理失败' then '新入' else '续费' end type, '未办理'status
from fa_dahui_qiyenianyue where yearpayment='{$thismoth}' and type!='转出');";
        Db::execute($sql);

        $sql = "delete from aa where exists (select businessnumber from fa_dahui_qiyenianyue where businessnumber=
aa.businessnumber and yearpayment= aa.yearpayment)";
        Db::execute($sql);

        $sql = "insert into fa_dahui_qiyenianyue (businessnumber,yearpayment, payingcompany, paymentbase, paymentamount, note, type)
select businessnumber,yearpayment, payingcompany, paymentbase, paymentamount, note, type
from aa where not exists (select businessnumber from fa_dahui_qiyenianyue where businessnumber=
aa.businessnumber and yearpayment= aa.yearpayment)";
        Db::execute($sql);

        $this->success("批量客户转入");
    }

    //http://dahui.test/admin/dahui/dingdan/xgjs?yearpayment=2019-07
    public function xgjs()
    {
        $thismoth = $this->request->get('yearpayment', '');
        if (empty($thismoth)) {
            $this->error("无效的年月！");
        }

        $sql = "update fa_dahui_qiyenianyue set
paymentbase=case when (select minimumcardinality from fa_dahui_gongshi where businesstype=(select businesstype from fa_dahui_qiyeputong where fa_dahui_qiyenianyue.businessnumber=fa_dahui_qiyeputong.businessnumber) and name=payingcompany)>paymentbase
then (select minimumcardinality from fa_dahui_gongshi where businesstype=(select businesstype from fa_dahui_qiyeputong where fa_dahui_qiyenianyue.businessnumber=fa_dahui_qiyeputong.businessnumber) and name=payingcompany) else paymentbase end,
paymentamount=case when (select minimumcardinality from fa_dahui_gongshi where businesstype=(select businesstype from fa_dahui_qiyeputong where fa_dahui_qiyenianyue.businessnumber=fa_dahui_qiyeputong.businessnumber) and name=payingcompany)>paymentbase
then (select minimumcardinality from fa_dahui_gongshi where businesstype=(select businesstype from fa_dahui_qiyeputong where fa_dahui_qiyenianyue.businessnumber=fa_dahui_qiyeputong.businessnumber) and name=payingcompany)*
(select proportion from fa_dahui_gongshi where businesstype=(select businesstype from fa_dahui_qiyeputong where fa_dahui_qiyenianyue.businessnumber=fa_dahui_qiyeputong.businessnumber) and name=payingcompany) else paymentamount end
where yearpayment='{$thismoth}' ";
        Db::execute($sql);

        $this->success("批量修改基数");
    }

    /**
     * 联动搜索 -- 业务+公司
     *  select businesstype as name  from fa_dahui_gongshi where 1 group by businesstype
     */
    public function cxselect()
    {
        $type = $this->request->get('type', '');
        $businesstype = $this->request->get('businesstype', '');

        $list = null;
        if ($type == 'businesstype') {
            $gsmodel = new \app\admin\model\dahui\Gongshi;
            $list = $gsmodel
                ->group('businesstype')
                ->field('businesstype as value, businesstype as name')
                ->select();
        } else if ($businesstype !== '') {
            $gsmodel = new \app\admin\model\dahui\Gongshi;
            $list = $gsmodel->where('businesstype', $businesstype)
                ->field('name as value, name')
                ->select();
        }

        $this->success('', null, $list);
    }

    public function import()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限

        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv'])) {
            $this->error(__('Unknown data format'));
        }

        $num = 0;
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $n = 0;
            $lastline = "";
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                $oldchar = array("\t", "\"");
                $newchar = array("", "");
                $line = str_replace($oldchar, $newchar, $line);

                if ($n == 0 || preg_match('/^".*"$/', $line)) {
//                    $filed = explode(',', $line);
//                    $max = count($filed);
//                    if ($max < 16 || $filed[0] != '序号' || $filed[1] != '淘宝名' || $filed[2] != '缴纳人姓名' || $filed[3] != '支付宝'
//                        || $filed[4] != '退款人姓名' || $filed[5] != '实退金额' || $filed[6] != '身份证' || $filed[7] != '缴纳日期'
//                        || $filed[8] != '月数' || $filed[9] != '缴纳基数' || $filed[10] != '缴纳金额' || $filed[11] != '新金额'
//                        || $filed[12] != '应退金额' || $filed[13] != '公司' || $filed[14] != '备注' || $filed[15] != '制表') {
//                        $this->error(__('错误的格式！'));
//                    }
                    //表头
//                    所属公司 合同期限开始 合同期限结束 业务类型 缴纳年月 身份证号 客户姓名 客户电话 户籍地址 现住地址 缴纳号码 缴纳公司 缴纳基数 缴纳金额 缴纳备注

                } else {
                    //内容
                    $line = $lastline.$line;
                    $filed = explode(',', $line);
//                    $size = count($filed);
//                    if ($size != $max) {
//                        $lastline = $line;
//                        $n++;
//                        continue;
//                    }

                    $params = array(
                        'ownedcompany' => $filed[0],
                        'contractperiod_from' => str_replace('/', '-', $filed[1]),
                        'contractperiod_to' => str_replace('/', '-', $filed[2]),
                        'businesstype' => $filed[3],
                        'yearpayment' => str_replace('.', '-', $filed[4]),
                        'idnumber' => $filed[5],
                        'name' => $filed[6],
                        'mobile' => $filed[7],
                        'address0' => $filed[8],
                        'address1' => $filed[9],
                        'paymentnumber' => $filed[10],
                        'payingcompany' => $filed[11],
                        'paymentbase' => $filed[12],
                        'paymentamount' => $filed[13],
                    );

                    if (empty($params['businesstype'])) {
                        $params['businesstype'] = '社保';
                    }

                    $row = $this->model
                        ->where('businesstype', $params['businesstype'])
                        ->where('idnumber', $params['idnumber'])
                        ->find();

                    $params = $this->setquanxianlog($params);
                    $row1 = new \app\admin\model\dahui\Qiyeputong;
                    if (!$row) {
                        $result = $row1->allowField(true)->save($params);
                        $row1->businessnumber = $row1->id;
                        $row1->save();
                        $params['businessnumber'] = $row1->id;
                    } else {
                        $params['businessnumber'] = $row->businessnumber;
                        $result = $row1->allowField(true)->save($params);
                    }

                    $kehu = \app\admin\model\dahui\Qiyekehu::get(['idnumber' => $params['idnumber']]);
                    if (!$kehu) {
                        $kehu = new \app\admin\model\dahui\Qiyekehu;
                        $result2 = $kehu->allowField(true)->save($params);
                    }

                    $nymodel = new \app\admin\model\dahui\Qiyenianyue();

                    $ny = $nymodel->where('businessnumber', $params['businessnumber'])
                        ->where('yearpayment', $params['yearpayment'])
                        ->find();

                    if ($ny) {
//                        $this->error(__('添加失败，系统已存在该客户该业务缴纳年月！'));
                        continue;
                    } else {
                        $result3 = $nymodel->allowField(true)->save($params);
                    }
                    $num++;
                }
                $n++;
            }
            fclose($file);

        }

        $this->success("成功导入记录 ".$num);
    }


    //设置权限记录
    function setquanxianlog($params)
    {
        if (!$params) {
            return $params;
        }
        $audit = $this->auth->check('dahui/dingdan/audit');
        $luru = $this->auth->check('dahui/dingdan/luru');
        $caozuo = $this->auth->check('dahui/dingdan/caozuo');
        $admin = $audit;

        if ($audit) {
            //审核员和管理员
            $params['auditman'] = $this->auth->nickname;
        } else if ($luru) {
            $params['luruman'] = $this->auth->nickname;
        } else if ($caozuo) {
            $params['opman'] = $this->auth->nickname;
        }

        return $params;
    }

    function setquanxianlog2($row)
    {
        if (!$row) {
            return $row;
        }
        $audit = $this->auth->check('dahui/dingdan/audit');
        $luru = $this->auth->check('dahui/dingdan/luru');
        $caozuo = $this->auth->check('dahui/dingdan/caozuo');
        $admin = $audit;

        if ($audit) {
            //审核员和管理员
            $row->auditman = $this->auth->nickname;
        } else if ($luru) {
            $row->luruman = $this->auth->nickname;
        } else if ($caozuo) {
            $row->opman= $this->auth->nickname;
        }

        return $row;
    }

    //http://dahui.test/admin/dahui/qiyeputong/getuserinfo?idnumber=43121
    public function getuserinfo($idnumber)
    {
        $kehu = \app\admin\model\dahui\Qiyekehu::get(['idnumber' => $idnumber]);
        $this->success("获取用户信息成功", null, $kehu);
    }

}
